// import React, { useEffect } from 'react';
// import ReactDOM, { render } from "react-dom";
// import { withLogin } from "@/plugins/hoc";
// import $axios from "@/plugins/request";
// import moment from "moment";
// import 'moment/locale/zh-cn';
// import { Button, Table, message, Popconfirm, Input } from 'antd';
// const { Search } = Input;
// import { useState } from 'react';
// import { useCallback } from 'react';
// moment.locale('zh-cn')


// function List(props) {
//   //删除
//   const removeItem = useCallback(async (id) => {
//     const { data } = await $axios.delete('/api/branch/' + id)
//     if (data.code != 1) {
//       return message.warning(data.message)
//     } else {
//       message.success('数据删除成功');
//       getDatalist(page)
//     }
//   }, [])
//   //增加
//   const addItem = useCallback(() => {
//     const { history, match } = props;
//     history.push(match.path.replace('/list', '') + '/add')
//   }, [])

//   //修改
//   const editItem = useCallback(async (id) => {
//     const { history, match } = props;
//     history.push(match.path.replace('/list', '') + '/edit/' + id)
//   })

//   const [datalist, setDatalist] = useState([]);
//   const [page, setPage] = useState(1);
//   const [pagesize, setPagesize] = useState(5);
//   const [total, setTotal] = useState([]);
//   const [branch, setBranch] = useState([])
//   // const []
//   const getDatalist = useCallback(async () => {
//     const { data: { data } } = await $axios.get('/api/branch', {
//       params: {
//         pagesize,
//         page, branch
//       }
//     })
//     setBranch(branch)
//     setTotal(data.total)
//     setDatalist(data.list)

//   }, [page, pagesize, branch])
//   useEffect(() => {
//     getDatalist();
//   }, [getDatalist])
//   const [columns] = useState([
//     {
//       title: '支部ID',
//       width: 230,
//       dataIndex: '_id'
//     },
//     {
//       title: '支部名称',
//       width: 200,
//       dataIndex: 'branch'
//     },
//     {
//       title: '支部创建时间',
//       dataIndex: 'create_time',
//       render: (text, row, index) => {
//         return moment(text).format("YYYY-MM-DD HH:mm:ss")
//       }
//     },
//     {
//       title: '支部更新时间',
//       dataIndex: 'create_time',
//       render: (text, row, index) => {
//         return moment(text).format("YYYY-MM-DD HH:mm:ss")
//       }
//     },
//     {
//       title: '操作',
//       render: (row) => {
//         return (
//           <>
//             <Button type="primary" size="small" style={{ marginRight: 10 }} onClick={() => {
//               editItem(row._id)
//             }}>编辑</Button>
//             <Popconfirm title="确定删除吗?" onConfirm={
//               () => {
//                 removeItem(row._id)
//               }
//             }>
//               <Button size="small" danger>删除</Button>
//             </Popconfirm>
//           </>
//         )
//       }
//     },
//   ])



//   //分页器
//   const panigation = {
//     size: 'small',
//     total: total,
//     showSizeChanger: true,
//     pageSizeOptions: [5, 10, 15, 20],
//     showTotal(total) {
//       return `共${total}条数据`
//     },
//     showQuickJumper: true,
//     showSizeChange: true,
//     onChange: (page, pagesize) => {
//       setPage(page)
//       setPagesize(pagesize)
//       getDatalist()
//     }

//   }
//   //搜索
//   const onSearch = useCallback((value) => {
//     console.log("value", value);
//     setBranch(value)
//     // getDatalist(value)
//   }, [])
//   return (
//     <div>
//       <div className="top">
//         <Search placeholder="搜索支部" onSearch={onSearch} style={{ width: 300, marginRight: 10 }} />
//         <Button type="primary" onClick={() => {
//           addItem()
//         }} style={{ marginBottom: 10, marginRight: 10 }} >添加支部</Button>
//       </div>
//       <Table rowKey="_id" columns={columns} dataSource={datalist} pagination={panigation} scroll={{ y: 500 }} />
//     </div>
//   )
// }

// export default List;

import React from "react";
import { Table, Input, Button, DatePicker, message } from "antd";
import $axios from "@/plugins/request";
import moment from "moment";
const { Search } = Input;
export default class EditTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      datalist: [],
      editArr: [],
      page: 1,
      pagesize: 5,
      total: 0
    };
  }


  getDatalist = (async () => {
    const { page, pagesize } = this.state;
    const { data: { data } } = await $axios.get('/api/branch', {
      params: {
        pagesize,
        page
      }
    })
    // console.log("data.list", data.list);
    this.setState({
      datalist: data.list,
      total: data.total
    })
  })
  componentDidMount() {
    this.getDatalist()
  }

  // 渲染出来input,输入的时候改变datalist的数据
  renderInput = (text, record, index, field) => {
    const { editArr } = this.state;
    return record.edit ? (
      <Input
        value={
          editArr[index] && editArr[index][field]
            ? editArr[index][field]
            : record[field]
        }
        onChange={(e) => this.inputChange(e, record, index, field)}
      // onPressEnter={(e) => this.handleSave(e, record)}
      // onBlur={(e) => this.handleSave(e, record)}
      />
    ) : (
      text
    );
  };
  //增加
  addItem = (() => {
    const { history, match } = this.props;
    history.push(match.path.replace('/list', '') + '/add')
  })

  renderDate = (text, record, index, field) => {
    const { editArr } = this.state;
    let value = editArr[index] && editArr[index][field]
      ? editArr[index][field]
      : record[field]
    // console.log('VALUE', value);
    value = moment(value)
    return record.edit ? (
      <DatePicker
        format="YYYY-MM-DD HH:mm:ss"
        showTime={{ defaultValue: value }}
        onChange={(e) => this.inputChange(e, record, index, field)}
      />
    ) : (
      moment(text).format("YYYY-MM-DD HH:mm:ss")
    );
  };
  // getData = useCallback(async () => {
  //   const { id } = props.match.params;
  //   const { data } = await $axios.get(`/api/branch/${id}`)
  //   setData(data.data)
  //   console.log("editdata", data);
  // })
  // 编辑表格
  edit = (record, id) => {
    const { datalist } = this.state;
    // // 浅拷贝下数据
    const newArr = [...datalist];
    // 找到index的值
    const index = newArr.findIndex((item) => item._id === id);
    // 利用splice方法删除原数据，新增新数据
    newArr.splice(index, 1, { ...record, edit: true });
    // 注意：一开始写法是const arr = newArr.splice(index, 1, { ...record, ...{ edit: true } });是错的，因为这个方法返回的是删除的那一条值
    this.setState({ datalist: newArr });
  };
  //删除
  removeItem = (async (id) => {
    const { data } = await $axios.delete('/api/branch/' + id)
    if (data.code != 1) {
      return message.warning(data.message)
    } else {
      message.success('数据删除成功');
      this.getDatalist(this.page)
    }
  })
  // input改变的时候
  inputChange = (e, record, index, field) => {
    let { editArr } = this.state;
    editArr[index] = record;
    record[field] = e.target.value;
    this.setState({ editArr });
  };

  // 一键保存所有数据
  // saveAll = () => {
  //   const { datalist } = this.state;
  //   const arr = datalist.map((item) => {
  //     return {
  //       ...item,
  //       edit: false,
  //     };
  //   });
  //   this.setState({ datalist: arr }, () => {
  //     console.log(datalist, "--datalist");
  //   });
  // };

  // 单条保存
  handleSave = (async (record, id) => {
    const { data } = await $axios.put(`/api/branch/${id}`, {
      branch: record.branch
    })
    if (data.code != 1) {
      return message.warning(data.message)
    } else {
      message.success('数据修改成功');
      this.getDatalist()
    }
    // console.log(data);
  });

  render() {
    const { datalist, total, page, pagesize } = this.state;

    const columns = [
      {
        title: '支部ID',
        width: 230,
        dataIndex: '_id',
        render: (text, record, index) =>
          this.renderInput(text, record, index, "_id"),
      },
      {
        title: '支部名称',
        width: 250,
        dataIndex: 'branch',
        render: (text, record, index) =>
          this.renderInput(text, record, index, "branch"),
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        render: (text, record, index) => {
          return moment(text).format("YYYY-MM-DD HH:mm:ss")
        }
      },
      {
        title: '修改时间',
        dataIndex: 'update_time',
        render: (text, record, index) => {
          return moment(text).format("YYYY-MM-DD HH:mm:ss")
        }
      },
      {
        title: "操作",
        dataIndex: "edit",
        render: (text, record, index) => {
          // console.log("record", record);
          return !record.edit ? (
            <>
              <Button type="primary" size="small" style={{ cursor: "pointer", marginRight: 10 }} onClick={() => this.edit(record, record._id)}>编辑</Button>
              <Button danger style={{ cursor: "pointer" }} size="small" onClick={() => this.removeItem(record._id)}>删除</Button>
            </>

          ) : (
            <Button type="primary" style={{ cursor: "pointer" }} size="small" onClick={() => this.handleSave(record, record._id)}>单条保存</Button>
          );
        },
      },
    ];
    const onSearch = ((value) => {
      console.log("value", value);
      // setBranch(value)
      // getDatalist(value)
    })
    const panigation = {
      size: 'small',
      total: total,
      showSizeChanger: true,
      pageSizeOptions: [5, 10, 15, 20],
      showTotal(total) {
        return `共${total}条数据`
      },
      showQuickJumper: true,
      onChange: (page, pagesize) => {
        this.setState({
          page,
          pagesize: pagesize
        }, () => {
          this.getDatalist()
        })
      }

    }
    return (
      <div style={{ width: "90%" }}>
        <div className="top">
          <Search placeholder="搜索支部" onSearch={onSearch} style={{ width: 300, marginRight: 10 }} />
          <Button type="primary" onClick={() => {
            this.addItem()
          }} style={{ marginBottom: 10, marginRight: 10 }} >添加支部</Button>
        </div>
        <Table
          rowKey="_id"
          dataSource={datalist}
          columns={columns}
          pagination={panigation}
          scroll={{ y: 480 }}
        />
        {/* <Button type="primary" onClick={() => {
          this.saveAll()
        }}>
          一键保存
        </Button> */}
      </div>
    );
  }
}